package cn.exrick.manager.service.impl;


import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.manager.mapper.TbItemCatMapper;
import cn.exrick.manager.mapper.TbItemDescMapper;
import cn.exrick.manager.mapper.TbItemMapper;
import cn.exrick.manager.mapper.TbOrderItemMapper;
import cn.exrick.manager.pojo.TbItem;
import cn.exrick.manager.pojo.TbItemDesc;
import cn.exrick.manager.pojo.TbItemExample;
import cn.exrick.manager.pojo.TbOrderItemExample;
import cn.exrick.manager.service.ItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    private final static Logger log= LoggerFactory.getLogger(ItemServiceImpl.class);

    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbItemDescMapper tbItemDescMapper;
    @Autowired
    private TbItemCatMapper tbItemCatMapper;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Resource
    private Destination topicDestination;
    @Autowired
    private JedisClient jedisClient;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;


    @Value("${PRODUCT_ITEM}")
    private String PRODUCT_ITEM;
    @Value("${IMAGE_ACCESS_URL}")
    private String imageUrl;
    @Value("${RECOMEED_PANEL}")
    private String RECOMEED_PANEL;

    @Override
    public TbItem getItemById(Long id) {
        TbItem tbItem=tbItemMapper.getItemById(id);
        dealImage(tbItem);

        TbItemDesc tbItemDesc=tbItemDescMapper.selectByPrimaryKey(id);
        tbItem.setDetail(tbItemDesc.getItemDesc());

        return tbItem;
    }

    private void dealImage(TbItem tbItem){
        List<String> images = Arrays.asList(tbItem.getImages());
        List<String> newImages = new ArrayList<>(images.size());
        for(String image : images){
            newImages.add(imageUrl + image);
        }
        tbItem.setImage(StringUtils.join(newImages,","));
    }

    @Override
    public TbItem getNormalItemById(Long id) {

        return tbItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public DataTablesResult getItemList(int draw, int start, int length, int cid,String recommend, String search,String status,String minDate,String maxDate,
                                        String orderCol, String orderDir) {

        DataTablesResult result=new DataTablesResult();

        //分页执行查询返回结果
        PageHelper.startPage(start/length+1,length);
        List<TbItem> list = tbItemMapper.selectItemByCondition(cid,recommend,"%"+search+"%",status,minDate,maxDate,orderCol,orderDir);
        list.forEach(tbItem -> dealImage(tbItem));
        PageInfo<TbItem> pageInfo=new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal((int)pageInfo.getTotal());

        result.setDraw(draw);
        result.setData(list);

        return result;
    }

    @Override
    public DataTablesResult getItemSearchList(int draw, int start, int length,int cid,String recommend, String search,String status,
                                              String minDate, String maxDate, String orderCol, String orderDir) {

        DataTablesResult result=new DataTablesResult();

        //分页执行查询返回结果
        PageHelper.startPage(start/length+1,length);
        List<TbItem> list = tbItemMapper.selectItemByMultiCondition(cid,recommend,"%"+search+"%",status,minDate,maxDate,orderCol,orderDir);
        list.forEach(tbItem -> dealImage(tbItem));
        PageInfo<TbItem> pageInfo=new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal(getAllItemCount(status,minDate,maxDate).getRecordsTotal());

        result.setDraw(draw);
        result.setData(list);

        return result;
    }

    @Override
    public DataTablesResult getAllItemCount(String status, String minDate, String maxDate) {
        TbItemExample example=new TbItemExample();
        TbItemExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(status)){
            criteria.andStatusEqualTo(Integer.parseInt(status));
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(StringUtils.isNotBlank(minDate)){
                criteria.andSaleDateGreaterThanOrEqualTo(dateFormat.parse(minDate));
            }

            if(StringUtils.isNotBlank(maxDate)){
                criteria.andSaleDateLessThanOrEqualTo(dateFormat.parse(maxDate));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Long count=tbItemMapper.countByExample(example);
        DataTablesResult result=new DataTablesResult();
        result.setRecordsTotal(Math.toIntExact(count));
        return result;
    }

    @Override
    public TbItem alertItemState(Long id, Integer state) {

        TbItem tbMember = getNormalItemById(id);
        tbMember.setStatus(state);
        tbMember.setUpdateTime(new Date());

        if (tbItemMapper.updateByPrimaryKey(tbMember) != 1){
            throw new XmallException("修改商品状态失败");
        }
        return getNormalItemById(id);
    }

    @Override
    public int deleteItem(Long id) {

        if(tbItemMapper.deleteByPrimaryKey(id)!=1){
            throw new XmallException("删除商品失败");
        }
        if(tbItemDescMapper.deleteByPrimaryKey(id)!=1){
            throw new XmallException("删除商品详情失败");
        }
        //发送消息同步索引库
       /* try {
            sendRefreshESMessage("delete",id);
        }catch (Exception e){
            log.error("同步索引出错");
        }*/
        return 0;
    }

    @Override
    public TbItem addItem(TbItem tbItem) {
        tbItem.setCreateTime(new Date());
        tbItem.setUpdateTime(new Date());
        tbItem.setIsRecommend(false);
        if(tbItemMapper.insert(tbItem)!=1){
            throw new XmallException("添加商品失败");
        }

        long id = tbItem.getId();

        TbItemDesc tbItemDesc=new TbItemDesc();
        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(tbItem.getDetail());
        tbItemDesc.setCreated(new Date());
        tbItemDesc.setUpdated(new Date());

        if(tbItemDescMapper.insert(tbItemDesc)!=1){
            throw new XmallException("添加商品详情失败");
        }
        //发送消息同步索引库
       /* try {
            sendRefreshESMessage("add",id);
        }catch (Exception e){
            log.error("同步索引出错");
        }*/
        return getNormalItemById(id);
    }

    @Override
    public TbItem updateItem(Long id, TbItem tbItem) {

        TbItem oldTbItem=getNormalItemById(id);

        if(tbItem.getImage().isEmpty()){
            tbItem.setImage(oldTbItem.getImage());
        }
        tbItem.setId(id);
        tbItem.setCreateBy(oldTbItem.getCreateBy());
        tbItem.setCreateTime(oldTbItem.getCreateTime());
        tbItem.setUpdateTime(new Date());
        tbItem.setIsRecommend(oldTbItem.getIsRecommend());
        if(tbItemMapper.updateByPrimaryKey(tbItem)!=1){
            throw new XmallException("更新商品失败");
        }

        TbItemDesc tbItemDesc=new TbItemDesc();

        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(tbItem.getDetail());
        tbItemDesc.setUpdated(new Date());
        tbItemDesc.setCreated(oldTbItem.getCreateTime());

        if(tbItemDescMapper.updateByPrimaryKey(tbItemDesc)!=1){
            throw new XmallException("更新商品详情失败");
        }
        //同步缓存
        deleteProductDetRedis(id);
        delRecommendRedis();
        //发送消息同步索引库
       /* try {
            sendRefreshESMessage("add",id);
        }catch (Exception e){
            log.error("同步索引出错");
        }*/
        return getNormalItemById(id);
    }

    /**
     * 删除推荐商品缓存
     */
    private void delRecommendRedis(){
        try {
            jedisClient.del(RECOMEED_PANEL);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 同步商品详情缓存
     * @param id
     */
    public void deleteProductDetRedis(Long id){
        try {
            jedisClient.del(PRODUCT_ITEM+":"+id);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 发送消息同步索引库
     * @param type
     * @param id
     */
    public void sendRefreshESMessage(String type,Long id) {
        jmsTemplate.send(topicDestination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage(type+","+String.valueOf(id));
                return textMessage;
            }
        });
    }

    @Override
    public void updateRecommendItem(List<Long> ids, int recommend) {
        tbItemMapper.updateRecommendItem(ids,recommend);
        delRecommendRedis();
    }

    @Override
    public List<TbItem> getStockNotEnoughItemList() {
        return tbItemMapper.getStockNotEnoughItemList();
    }

    @Override
    public boolean checkItemHasRelatedOrder(List<Long> ids) {
        List<String> itemIds = new ArrayList<>();
        for(Long id : ids){
            itemIds.add(String.valueOf(id));
        }
        TbOrderItemExample example = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria = example.createCriteria();
        criteria.andItemIdIn(itemIds);
        long count = tbOrderItemMapper.countByExample(example);
        return count > 0;
    }
}
